package com.zmq.ha.client.util;
/**
 * 基于推特SnowFlake算法的Java版本
 * 依据 42bit 的时间特性，该随机数可以维持到2080年
 * 整个随机数为64bit ---> long类型长度  相比UUID具备空间优势和时序性
 * @author Administrator
 *
 */
public class SnowflakeUtil {

    private long workerId;
    private long sequence = 0L;
    private long twepoch = 1262275200000L; //2010-01-01 00:00:00
    private long workerIdBits = 10L; //节点ID长度(2^10)
    private long maxWorkerId = -1L ^ (-1L << workerIdBits); //最大支持机器节点数1024
    private long sequenceBits = 12L; //序列号12位(4096)
    private long workerIdShift = sequenceBits; //机器节点左移12位
    private long timestampLeftShift = sequenceBits + workerIdBits ; //时间毫秒数左移22位
    private long sequenceMask = -1L ^ (-1L << sequenceBits); // 最大支持数4095，既是4096
    private long lastTimestamp = -1L; //上一次记录的时间毫秒数据
    
    private static class IdGenHolder {
        private static final SnowflakeUtil instance = new SnowflakeUtil();
    }
    
    public static SnowflakeUtil get(){
        return IdGenHolder.instance;
    }

    public SnowflakeUtil() {
        this(1001L);//传入机器节点,写到配置文件
    }

    public SnowflakeUtil(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;
    }
    
    public synchronized long nextId() {
    	//获取当前毫秒数
        long timestamp = timeNowMillis(); 
        //如果服务器时间有问题(时钟后退) 报错。
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format(
                    "Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        //在同一毫秒内
        if (lastTimestamp == timestamp) {
            //sequence自增，因为sequence只有12bit，所以和sequenceMask相与一下，去掉高位
            sequence = (sequence + 1) & sequenceMask;
            //判断是否溢出,也就是每毫秒内超过4095，当为4096时，与sequenceMask相与，sequence就等于0
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp); //自旋等待到下一毫秒
            }
        } else {
        	//如果和上次生成时间不同,重置sequence，就是下一毫秒开始，sequence计数重新从0开始累加
            sequence = 0L; 
        }
        lastTimestamp = timestamp;
       
         /**
          *  000000000000000000000000000000000000000000  0000000000       000000000000
          *  |-----------------42bit时间毫秒-------------|  |-10bit机器码-|    |-12位特征码-|
          */
         return ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeNowMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = timeNowMillis();
        }
        return timestamp;
    }

    protected long timeNowMillis() {
        return System.currentTimeMillis();
    }
    
    
}